<template>
    <view class="clock-page">
        <!-- 状态栏占位 -->
        <!-- 背景图1：右上角装饰 -->
        <view class="background-image" :style="{
            backgroundImage: `url(${public_img}/img/backClock1.jpg)`,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            backgroundRepeat: 'no-repeat'
        }"></view>
        <!-- 背景图2：底层铺满 -->
        <view class="background-image" :style="{
            backgroundImage: `url(${public_img}/img/backClock2.png)`,
            backgroundSize: '290px 220px',
            backgroundPosition: 'top right',
            backgroundRepeat: 'no-repeat'
        }"></view>
        <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

        <!-- 自定义导航栏 -->
        <view class="custom-nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
            <!-- 返回按钮 -->
            <view class="nav-back" @click="goBack">
                <uni-icons type="left" size="20" color="#333333"></uni-icons>
            </view>
            <!-- 标题 -->
            <view class="nav-title">打卡任务</view>
        </view>
        <!-- 添加空标签 -->
        <view style="height: 70px;"></view>
        <!-- 左侧文字 -->
        <view class="quote-text">
            <text class="quote-line font-one">不是看到了希望才坚持</text>
            <text class="quote-line font-two">而是坚持才会看到希望</text>
        </view>

        <!-- 添加空标签 -->
        <view style="height: 23px;"></view>
        <!-- 主要内容区域 -->
        <view class="main-content">
            <!-- 连续打卡部分 -->
            <view class="check-in-section">
                <view class="check-in-header">
                    <view class="check-in-title">
                        <text style="font-weight: 700;">连续打卡</text>
                        <text class="highlight-red">{{ continuousDays }}</text>
                        <text class="check-in-title" style="font-weight: 700;">天</text>
                    </view>
                    <view class="reminder-box">
                        <text class="reminder-text">打卡提醒</text>
                        <view class="switch-wrapper">
                            <switch :checked="reminderEnabled" @change="toggleReminder" color="#007AFF" />
                        </view>
                    </view>
                </view>

                <!-- 打卡天数圆圈 -->
                <view class="check-in-days">
                    <view class="day-item" v-for="(day, index) in checkInDays" :key="index">
                        <view class="day-circle" :class="{ 'day-pending': !day.completed }">
                            <image v-if="day.completed" class="check-icon" :src="public_img + '/img/yellow.png'"
                                mode="aspectFit">
                            </image>
                            <text v-else class="day-points">+{{ day.points }}</text>
                        </view>
                        <text class="day-label">{{ day.day }}天</text>
                    </view>
                </view>
            </view>

            <!-- 今日任务部分 -->
            <view class="tasks-title">今日任务</view>
            <view class="task-list">
                <view class="task-item" v-for="(task, index) in taskList" :key="index">
                    <view class="task-info">
                        <view class="task-name-row">
                            <text class="task-name">{{ task.name }}</text>
                            <text class="task-points">+{{ task.points }}积分</text>
                        </view>
                        <text class="task-desc">{{ task.desc }}</text>
                    </view>
                    <view class="task-action">
                        <view class="check-in-btn" @click="goToCheckIn(task)">去打卡</view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { public_img } from '@/static/public.js';
export default {

    data() {
        return {
            statusBarHeight: 0, // 状态栏高度
            continuousDays: 1, // 连续打卡天数
            reminderEnabled: true, // 打卡提醒开关状态
            public_img: public_img,
            checkInDays: [
                { day: 1, completed: true, points: 0 },
                { day: 2, completed: false, points: 10 },
                { day: 3, completed: false, points: 15 },
                { day: 4, completed: false, points: 20 },
                { day: 5, completed: false, points: 30 },
                { day: 6, completed: false, points: 40 },
                { day: 7, completed: false, points: 60 }
            ],
            taskList: [
                { name: '礼盒商城', points: 30, desc: '制作首页' },
                { name: '礼盒商城', points: 30, desc: '制作分类' },
                { name: '礼盒商城', points: 30, desc: '制作打卡任务' },
                { name: '礼盒商城', points: 30, desc: '制作购物车' },
                { name: '礼盒商城', points: 30, desc: '任务我的' }
            ]
        };
    },
    onLoad() {
        // 获取设备状态栏高度
        this.getStatusBarHeight();
        // 隐藏TabBar
        uni.hideTabBar({
            animation: false
        });

        // 加载打卡数据
        this.loadCheckInData();

        // 记录进入打卡页面时的来源页面
        // 获取页面栈
        const pages = getCurrentPages();
        if (pages.length > 1) {
            // 如果有前序页面，记录前序页面的路径
            const prevPage = pages[pages.length - 2];
            const fromPage = '/' + prevPage.route;
            uni.setStorageSync('clockFromPage', fromPage);
            console.log('记录来源页面（非TabBar）:', fromPage);
        } else {
            // 如果页面栈只有当前页面，说明是从TabBar进入的
            // 从全局存储获取当前TabBar页面（在其他TabBar页面的onShow中记录）
            // 注意：此时可能其他TabBar页面的onShow还没执行，所以onShow中会再次记录
            const currentTabBarPage = uni.getStorageSync('currentTabBarPage');
            if (currentTabBarPage) {
                uni.setStorageSync('clockFromPage', currentTabBarPage);
                console.log('onLoad记录来源页面（TabBar）:', currentTabBarPage);
            }
            // 如果没有获取到，会在onShow中再次尝试获取
        }
    },
    onShow() {
        // 页面显示时隐藏TabBar
        uni.hideTabBar({
            animation: false
        });

        // 在onShow中也记录来源页面（确保每次进入都能记录）
        // 获取页面栈
        const pages = getCurrentPages();
        if (pages.length > 1) {
            // 如果有前序页面，记录前序页面的路径
            const prevPage = pages[pages.length - 2];
            const fromPage = '/' + prevPage.route;
            uni.setStorageSync('clockFromPage', fromPage);
            console.log('onShow记录来源页面（非TabBar）:', fromPage);
        } else {
            // 如果页面栈只有当前页面，说明是从TabBar进入的
            // 从全局存储获取当前TabBar页面（在其他TabBar页面的onShow中记录）
            const currentTabBarPage = uni.getStorageSync('currentTabBarPage');
            if (currentTabBarPage) {
                uni.setStorageSync('clockFromPage', currentTabBarPage);
                console.log('onShow记录来源页面（TabBar）:', currentTabBarPage);
            } else {
                // 如果还是没有，检查是否已经有记录的来源页面
                const existingFromPage = uni.getStorageSync('clockFromPage');
                if (!existingFromPage) {
                    // 如果都没有，使用默认值首页
                    const defaultPage = '/pages/index/index';
                    uni.setStorageSync('clockFromPage', defaultPage);
                    console.log('onShow未获取到TabBar页面，使用默认首页:', defaultPage);
                }
            }
        }
    },
    onHide() {
        // 页面隐藏时显示TabBar
        uni.showTabBar({
            animation: false
        });
    },
    onUnload() {
        // 页面卸载时显示TabBar
        uni.showTabBar({
            animation: false
        });
    },
    methods: {
        // 获取设备状态栏高度
        getStatusBarHeight() {
            try {
                const systemInfo = uni.getSystemInfoSync();
                this.statusBarHeight = systemInfo.statusBarHeight || 0;
            } catch (err) {
                console.error('获取状态栏高度失败', err);
                this.statusBarHeight = 20;
            }
        },

        // 加载打卡数据
        loadCheckInData() {
            // 从本地存储加载连续打卡天数
            const savedDays = uni.getStorageSync('continuousCheckInDays');
            if (savedDays) {
                this.continuousDays = savedDays;
            }

            // 从本地存储加载提醒开关状态
            const savedReminder = uni.getStorageSync('checkInReminder');
            if (savedReminder !== null && savedReminder !== undefined) {
                this.reminderEnabled = savedReminder;
            }

            // 更新打卡天数圆圈状态
            this.updateCheckInDays();
        },

        // 更新打卡天数圆圈状态
        updateCheckInDays() {
            this.checkInDays.forEach((day, index) => {
                day.completed = index < this.continuousDays;
            });
        },

        // 切换打卡提醒开关
        toggleReminder(e) {
            this.reminderEnabled = e.detail.value;
            // 保存到本地存储
            uni.setStorageSync('checkInReminder', this.reminderEnabled);
            console.log('打卡提醒开关:', this.reminderEnabled ? '开启' : '关闭');
        },

        // 去打卡
        goToCheckIn(task) {
            console.log('去打卡:', task);
            // TODO: 实现打卡逻辑
            uni.showToast({
                title: '打卡成功',
                icon: 'success'
            });
        },

        // 返回上一页（自动返回跳转前的页面）
        goBack() {
            // 先显示TabBar
            uni.showTabBar({
                animation: false
            });

            // 获取当前页面栈（数组，最后一个元素是当前页面）
            const pages = getCurrentPages();
            console.log('当前页面栈', pages);

            // 获取记录的来源页面
            const fromPage = uni.getStorageSync('clockFromPage');
            console.log('来源页面:', fromPage);

            // 页面栈长度 > 1 说明有前序页面，直接返回上一页
            if (pages.length > 1) {
                uni.navigateBack({
                    delta: 1, // 返回上一级页面
                    success: () => {
                        console.log('返回上一页成功');
                        // 延迟清除存储，确保返回完成
                        setTimeout(() => {
                            uni.removeStorageSync('clockFromPage');
                        }, 300);
                    },
                    fail: (err) => {
                        console.error('返回上一页失败', err);
                        // 失败时尝试跳转到记录的来源页面
                        if (fromPage) {
                            this.navigateToFromPage(fromPage);
                        } else {
                            // 如果也没有来源页面，兜底跳转到首页
                            uni.switchTab({ url: '/pages/index/index' });
                            uni.removeStorageSync('clockFromPage');
                        }
                    }
                });
            } else {
                // 页面栈长度 = 1 说明直接从TabBar进入，跳转到记录的来源页面
                if (fromPage) {
                    this.navigateToFromPage(fromPage);
                } else {
                    // 如果没有记录来源页面，默认返回首页
                    uni.switchTab({ url: '/pages/index/index' });
                    console.log('没有记录来源页面，默认返回首页');
                    // 清除可能存在的旧存储
                    uni.removeStorageSync('clockFromPage');
                }
            }
        },

        // 跳转到来源页面
        navigateToFromPage(fromPage) {
            // 判断是否是TabBar页面
            const tabBarPages = [
                '/pages/index/index',
                '/pages/type/index',
                '/pages/clock/index',
                '/pages/shoppingCar/index',
                '/pages/mine/index'
            ];

            if (tabBarPages.includes(fromPage)) {
                // 是TabBar页面，使用switchTab
                uni.switchTab({
                    url: fromPage,
                    success: () => {
                        console.log('跳转到TabBar页面成功:', fromPage);
                        // 延迟清除存储，确保跳转完成
                        setTimeout(() => {
                            uni.removeStorageSync('clockFromPage');
                        }, 300);
                    },
                    fail: (err) => {
                        console.error('跳转到TabBar页面失败:', err);
                        // 失败时兜底跳转到首页
                        uni.switchTab({ url: '/pages/index/index' });
                        uni.removeStorageSync('clockFromPage');
                    }
                });
            } else {
                // 不是TabBar页面，使用navigateTo
                uni.navigateTo({
                    url: fromPage.startsWith('/') ? fromPage : '/' + fromPage,
                    success: () => {
                        console.log('跳转到普通页面成功:', fromPage);
                        // 延迟清除存储，确保跳转完成
                        setTimeout(() => {
                            uni.removeStorageSync('clockFromPage');
                        }, 300);
                    },
                    fail: (err) => {
                        console.error('跳转到普通页面失败:', err);
                        // 失败时兜底跳转到首页
                        uni.switchTab({ url: '/pages/index/index' });
                        uni.removeStorageSync('clockFromPage');
                    }
                });
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.clock-page {
    width: 100%;
    min-height: 100vh;
    position: relative;
    /* 全局背景图 */
}

.background-image {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 0;
    pointer-events: none;
}

/* 状态栏占位 */
.status-bar {
    width: 100%;
    background-color: transparent;
}

/* 自定义导航栏 */
.custom-nav-bar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    background-color: transparent;
}

.nav-back {
    position: absolute;
    left: 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60rpx;
    height: 60rpx;
    z-index: 1001;
}

.nav-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
    text-align: center;
}

/* 左侧文字 */
.quote-text {
    position: relative;
    z-index: 111;
    display: flex;
    flex-direction: column;
}

.quote-line {
    font-size: 16px;
    color: #ffffff;
    line-height: 1.6;
    font-weight: 700;
}

.font-one {
    margin-left: 15px;
}

.font-two {
    margin-left: 55px;
}


/* 主要内容区域 */
.main-content {
    position: relative;
    z-index: 100;
}

/* 连续打卡部分 */
.check-in-section {
    background-color: #ffffff;
    padding: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.check-in-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
}

.check-in-title {
    font-size: 17px;
    color: #505050;
}

.highlight-red {
    color: #ff0000;
}

.reminder-box {
    display: flex;
    align-items: center;
    gap: 15rpx;
}

.reminder-text {
    font-size: 28rpx;
    color: #333333;
}

.switch-wrapper {
    transform: scale(0.7);
    transform-origin: center;
}

/* 打卡天数圆圈 */
.check-in-days {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.day-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10rpx;
}

.day-circle {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
}

.day-pending {
    background-color: #eeeeee;
}

.check-icon {
    width: 42px;
    height: 42px;
}

.day-points {
    font-size: 14px;
    color: #9f9898;
    font-weight: bold;
}

.day-label {
    font-size: 15px;
    color: #505050;
    font-weight: 700;
}

.tasks-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
    padding: 10px 0;
    margin-left: 7px;
}

.task-list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
}

.task-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 9px;
    background-color: rgba(255, 255, 255, 0.6);
    border-radius: 10rpx;
    margin: 0 3px;
}

.task-info {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.task-name {
    font-size: 18px;
    color: #505050;
}

.task-points {
    font-size: 14px;
    color: #ff8d1a;
    margin-left: 10px;
}

.task-desc {
    font-size: 14px;
    color: #bababa;
}

.task-action {
    margin-left: 20rpx;
}

.check-in-btn {
    background-color: #ffc300;
    color: white;
    border: none;
    border-radius: 50px;
    font-size: 28rpx;
    font-weight: 700;
    padding: 5px 21px;
}

.check-in-btn::after {
    border: none;
}
</style>
